package kr.hkit.androidcomplete02.file;

import kr.hkit.androidcomplete02.R;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.text.TextUtils;

public class SettingsFragment extends PreferenceFragment {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		addPreferencesFromResource(R.xml.preferences);

		setOnPreferenceChange(findPreference("userNameOpen"));
		setOnPreferenceChange(findPreference("pref_syncConnectionType"));
		setOnPreferenceChange(findPreference("edittext_preference"));
		setOnPreferenceChange(findPreference("autoUpdate_ringtone"));
		setOnPreferenceChange(findPreference("list_preference"));
	}

	private void setOnPreferenceChange(Preference mPreference) {
		mPreference.setOnPreferenceChangeListener(onPreferenceChangeListener);

		onPreferenceChangeListener.onPreferenceChange(
				mPreference,
				PreferenceManager.getDefaultSharedPreferences(
						mPreference.getContext()).getString(
						mPreference.getKey(), ""));
	}

	private Preference.OnPreferenceChangeListener onPreferenceChangeListener = new Preference.OnPreferenceChangeListener() {
		@Override
		public boolean onPreferenceChange(Preference preference, Object newValue) {
			String stringValue = newValue.toString();

			if (preference instanceof EditTextPreference) {
				preference.setSummary(stringValue);
			} else if (preference instanceof ListPreference) {
				ListPreference listPreference = (ListPreference) preference;
				int index = listPreference.findIndexOfValue(stringValue);
				preference
						.setSummary(index >= 0 ? listPreference.getEntries()[index]
								: null);
			} else if (preference instanceof RingtonePreference) {
				if (TextUtils.isEmpty(stringValue)) {
					preference.setSummary("무음으로 설정됨");
				} else {
					Ringtone ringtone = RingtoneManager.getRingtone(
							preference.getContext(), Uri.parse(stringValue));
					if (ringtone == null) {
						preference.setSummary(null);
					} else {
						String name = ringtone
								.getTitle(preference.getContext());
						preference.setSummary(name);
					}
				}
			}
			return true;
		}
	};
}
